package cn.kgc.service.impl;

import cn.kgc.constant.MessageInfoType;
import cn.kgc.entity.Messageinfo;
import cn.kgc.mapper.MessageinfoMapper;
import cn.kgc.service.SenderMessageInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wangyue
 * @version 1.0
 */
@Service("senderMessageInfoService")
public class SenderMessageInfoServiceImpl implements SenderMessageInfoService {
    @Resource
    private MessageinfoMapper messageinfoMapper;

    @Override
    public Messageinfo getTransmessage(String id) {
        return messageinfoMapper.selectById(id);
    }

    /**
     * 消息没有发送到队列中,将消息再次保存到数据库中
     */
    @Transactional
    @Override
    public Messageinfo messageSendReturn(
            String exchange, String routingKey,
            String body, int sequence,String serviceName,long delayTime
    ) {
        Messageinfo messageinfo = Messageinfo.builder()
                //交换机
                .exchange(exchange)
                //路由key
                .routingkey(routingKey)
                //消息内容
                .payload(body)
                //消息发送的次数
                .sequence(sequence)
                //消息的状态为发送状态
                .type(MessageInfoType.SEND.getType())
                //延迟时间
                .delaytime(delayTime)
                //哪个微服务发送的消息
                .service(serviceName).build();
        messageinfoMapper.insert(messageinfo);
        return messageinfo;
    }

    /**
     * 发送消息之前保存消息
     */
    @Override
    public Messageinfo messageSendReady(
            String exchange,String routingKey,
            String body,String serviceName,long delayTime
    ) {
        return messageSendReturn(exchange,routingKey,body,1,serviceName,delayTime);
    }

    @Override
    public void messageSendSuccess(String id) {
        messageinfoMapper.deleteById(id);
    }

    /**
     * 查询应该发送到队列中但是发送失败的消息
     */
    @Override
    public List<Messageinfo> listReadyMessage() {
        LambdaQueryWrapper<Messageinfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Messageinfo::getType,MessageInfoType.SEND.getType());
        return messageinfoMapper.selectList(queryWrapper);
    }

    /**
     * 信息重新发送,发送的次数+1
     */
    @Override
    public void messageResend(String id) {
        Messageinfo messageinfo = messageinfoMapper.selectById(id);
        messageinfo.setSequence(messageinfo.getSequence()+1);
        messageinfoMapper.updateById(messageinfo);
    }

    /**
     * 信息发送的次数超过最大发送次数,将消息的状态改为死亡状态
     */
    @Override
    public void messageDead(String id) {
        Messageinfo messageinfo = messageinfoMapper.selectById(id);
        messageinfo.setType("SENDER:"+MessageInfoType.DEAD.getType());
        messageinfoMapper.updateById(messageinfo);
    }
}
